/**
 *
 */
package com.longrise.android.byjk.plugins.login;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.android.byjk.plugins.main.UpdataAPK;
import com.longrise.android.byjk.advertisement.admanager.ADManager;
import com.longrise.android.byjk.plugins.main.MainActivity;
import com.longrise.common.base.BaseActivity;
import com.longrise.android.byjk.common.Control;
import com.longrise.common.utils.FolderConstants;
import com.longrise.android.byjk.common.UrlConstants;
import com.longrise.android.byjk.model.UserInfor;
import com.longrise.common.permission.PermissionUtil;
import com.longrise.android.byjk.plugins.publicWeb.PublicWebActivity;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.datasource.remote.ReloginBean;
import com.longrise.common.utils.AppUtil;
import com.longrise.common.datasource.local.sp.CacheUtils;
import com.longrise.common.utils.DZZWTools;
import com.longrise.android.byjk.utils.FileUtil;
import com.longrise.common.utils.NetUtil;
import com.longrise.filedownloader.ExternalStorageUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * simple introduction
 * <p/>
 * <p/>
 * detailed comment
 *
 * @author callxkj 2015-12-31
 * @see
 * @since 1.0
 */
public class LaunchActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "LaunchActivity";
    private static final String ISNOTFIRSTINSTALL = "isnotfirstinstall"; //是否是第一次安装
    public static final int LOADMAIN = 1;
    private static final int LOADLOGIN = 2;
    private static final int GUIDE = 3;
    private RelativeLayout mRootView;
    private EntityBean fbean;
    private String fusername;
    private boolean FLAG_CLOSE = false;
    private UpdataAPK mUpdataAPK;
    private RelativeLayout mRLfirst;
    private RelativeLayout mRlad;
    private TextView mTvskip;
    private Disposable mTimersubscribe;
    private Button mBtmflq;
    private ImageView mIvlauanch;


    @Override
    public int getContentViewId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_launch;
    }

    @Override
    public void setStatusBarColor() {
        super.setStatusBarColor();
        AppUtil.setFullScreen(this);
    }

    @Override
    public void initView() {
        mRootView = (RelativeLayout) findViewById(R.id.launch_root);
        mRLfirst = (RelativeLayout) findViewById(R.id.launch_first);
        mRlad = (RelativeLayout) findViewById(R.id.launch_ad);
        mTvskip = (TextView) findViewById(R.id.launch_skip_tv);
        mBtmflq = (Button) findViewById(R.id.launch_mflq_bt);
        mIvlauanch = (ImageView) findViewById(R.id.launch_iv);
        adjustLaunchImage();
        initAnim();
        UserInfor.getInstance().setVipstate(0);

    }


    /**
     * 初始化软件的文件夹
     */
    private void initFolder() {
        FileUtil.createFolder(FolderConstants.VIDEO_DIR); //视频文件夹
    }

    private void adjustLaunchImage() {
        int height = AppUtil.getScreenHeight();
        if (height < 900) {
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mIvlauanch.getLayoutParams();
            layoutParams.setMargins(0, AppUtil.dip2px(50), 0, 0);
            mIvlauanch.setLayoutParams(layoutParams);
        }
    }

    /**
     * alpha动画
     */
    private void initAnim() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(mRootView, "Alpha", 0, 1);
        animator.setDuration(2000);
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                initSetting();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                checkNeedUpdate();
                FLAG_CLOSE = true;
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animator.start();
    }

    private void initSetting() {
        boolean isOld = CacheUtils.getBoolean(ISNOTFIRSTINSTALL); //是否是已经安装过的
        if (!isOld) {//新安装的软件 做一些初始化设置
            Control.setIsChooseAreaTips(true);
            Control.setGuideView(true);
            Control.setIsHomeFragmentTips(true);
            CacheUtils.setBoolean(ISNOTFIRSTINSTALL, true);
        }

        //隐藏引导页
        Control.setGuideView(false);
    }

    /**
     * 判断是否是去引导页还是登陆页还是直接登陆
     */
    private void checkVersion() {
        boolean guideView = Control.isGuideView();
        if (guideView) {
            loadGuideView();
        } else {
            boolean netWorkEnable = NetUtil.checkNetEnable();
            if (netWorkEnable) {
                toLogin();
            } else {
                loadLogin();
            }
        }
    }


    private void toLogin() {
        long currentTime = System.currentTimeMillis();
        ReloginBean reloginBean = LoadDataManager.getInstance().getReloginBean();
        if (reloginBean != null) {
            long firstTime = reloginBean.getTime();
            long time = currentTime - firstTime;
            //604800000 一周
            if (time != 0 && time < 604800000) {
                reloginBean.setServiceName("bbt_login_sUserToken");
                reloginBean.setServiceUrl(UrlConstants.BaseUrl);
                LoadDataManager.getInstance().setReloginBean(reloginBean);
                login(reloginBean);
            } else {
                loadLogin();
            }
        } else {
            loadLogin();
        }
    }

    /**
     * 自动登录
     */
    private void login(ReloginBean requsetInfo) {
        fbean = requsetInfo.getBean();
        UserController.getInstance().login(UserController.LAUNCH, this, fbean, new UserCallback() {
            @Override
            public void onSuccess(int status, String des) {
                //自动登录取消提示
                // DZZWTools.showToast(LaunchActivity.this, des, 2 * 1000);
                if (status == UserCallback.HOME_PAGE) {
                    if ("1".equals(UserInfor.getInstance().getIsindexadsshow())) {
                        showLaunchAd();
                    } else {
                        loadMain();
                    }
                }
            }

            @Override
            public void onFail(String des) {
                DZZWTools.showToast(LaunchActivity.this, des, 2 * 1000);
                loadLogin();
            }

            @Override
            public void onFinish() {
                DZZWTools.dismissDialog(null);
            }
        });
    }

    /**
     * 去引导页
     */
    private void loadGuideView() {
        Intent intent = new Intent(this, GuideActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 去登陆界面
     */
    private void loadLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 直接去主界面
     * flag 该用户可以跳转到
     */
    private void loadMain() {
        mRxmanager.removeDisposable(mTimersubscribe);
        Intent intent = new Intent(LaunchActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转到广告页面 费率相关
     */
    private void toADpage() {
        mRxmanager.removeDisposable(mTimersubscribe);
        EntityBean bean = new EntityBean();
        bean.set("devicetype", "android");
        bean.set("urltype", "flhd");
        EntityBean fbean = new EntityBean();
        fbean.set("bean", bean);
        showLoadingDialog();
        LoadDataManager.getInstance().callService(null, UrlConstants.BaseUrl,
                "bbt_getAppEntryPath", fbean, new LoadDataManager.OnRequestCallListener() {
                    @Override
                    public void onSuccess(String key, String service, Object result) {
                        try {
                            if (result != null) {
                                EntityBean bean1 = (EntityBean) result;
                                EntityBean resultBean = bean1.getBean("result");
                                int resultstate = (Integer) bean1.get("resultstate");
                                String resultdesc = bean1.getString("resultdesc");
                                if (resultstate == 1) {
                                    String pageurl = resultBean.getString("pageurl");
                                    Bundle bundle = new Bundle();
                                    int screenWidth = AppUtil.getScreenWidth();
                                    String userid = UserInfor.getInstance().getUserid();
                                    int widthDP = AppUtil.px2dip(screenWidth);
                                    pageurl = pageurl + "?userid=" + userid + "&screenwidth=" + widthDP;
                                    bundle.putString(PublicWebActivity.URL, pageurl);
                                    Intent intentMain = new Intent(LaunchActivity.this, MainActivity.class);
                                    Intent intentAd = new Intent(LaunchActivity.this, PublicWebActivity.class);
                                    intentAd.putExtras(bundle);
                                    Intent[] intents = new Intent[2];
                                    intents[0] = intentMain;
                                    intents[1] = intentAd;
                                    startActivities(intents);
                                    finish();
                                } else {
                                    showToast(resultdesc);
                                    loadLogin();
                                }
                            } else {
                                loadLogin();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            loadLogin();
                        }
                    }

                    @Override
                    public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                        showToast(AppUtil.getString(R.string.nonetwork));
                        loadLogin();
                    }

                    @Override
                    public void onFinished(String key, String service) {
                        dismissLoadingDialog();
                    }
                });


    }


    private void checkCacheSpace() {
        boolean shouldTips = ExternalStorageUtils.isShouldTips();
        if (shouldTips) {
            String tips = getResources().getString(R.string.nocachespace);
            DZZWTools.showToast(this, tips, 1);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 获取存储权限
     */
    private void initPermission() {
        PermissionUtil.getInstance().requestPermission(this, PermissionUtil.Permission.STORAGE,
                getString(R.string.location_permission), getString(R.string.location_permission_hint),
                new PermissionUtil.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        initFolder();
                        checkCacheSpace();
                        ADManager.getInstance().init(FolderConstants.CACHE_DIR);//将广告文件放在缓存目录便于清理
                        checkVersion();
                    }

                    @Override
                    public void onDenied() {

                    }
                });
    }

    /**
     * 展示开屏广告
     */
    private void showLaunchAd() {
        mRlad.setVisibility(View.VISIBLE);
        mRLfirst.setVisibility(View.GONE);
        mTvskip.setOnClickListener(this);
        mBtmflq.setOnClickListener(this);
        mTimersubscribe = Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        long result = 4;
                        result = result - aLong;
                        if (result >= 0) {
                            return result;
                        } else {
                            return (long) 0;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (aLong <= 1) {
                            mTvskip.setText("跳过");
                        } else {
                            mTvskip.setText(aLong - 1 + "S跳过");
                        }
                        if (aLong <= 0) {
                            loadMain();
                        }
                    }
                });
        mRxmanager.addDisposable(mTimersubscribe);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.launch_skip_tv: //跳过
                loadMain();
                break;
            case R.id.launch_mflq_bt: // 立即领奖
                toADpage();
                break;
        }
    }

    /**
     * 检查app是否需要升级
     */
    private void checkNeedUpdate() {
        mUpdataAPK = new UpdataAPK(this, getResources().getString(R.string.leapAppName), true);
        mUpdataAPK.setCheckVersionListener(new UpdataAPK.CheckVersionListener() {
            @Override
            public void onCheckVersion(int mark) {
                if (mark == 0 || mark == -2) { //用户点击取消更新,或者app没有更新
                    // ,或者请求版本的接口错误 就进入app
                    initPermission();
                }
            }
        });
        mUpdataAPK.checkVersion();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //在动画没显示全的情况下不准用户关闭launch页面,防止更新dialog弹出bug
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (FLAG_CLOSE) {
                mUpdataAPK.setCanShowDialog(false);
                finish();
                MobclickAgent.onKillProcess(mContext);
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
